#ifndef __BLOCK_QUEUE_HPP__
#define __BLOCK_QUEUE_HPP__

#include <iostream>
#include <string>
#include <queue>
#include <pthread.h>

using namespace std;

template <class T>
class BlockQueue
{
private:
    bool IsFull()
    {
        return _block_queue.size() == _cap;
    }
    bool IsEmpty()
    {
        return _block_queue.empty();
    }

public:
    BlockQueue(int cap) : _cap(cap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_produck_cond, nullptr);
        pthread_cond_init(&_consum_cond, nullptr);
    }
    void Enqueue(T &in)
    {
        pthread_mutex_lock(&_mutex);
        while (IsFull())
        {
            pthread_cond_wait(&_produck_cond, &_mutex);
        }
        // cout << in << endl;
        _block_queue.push(in);
        pthread_cond_signal(&_consum_cond);
        pthread_mutex_unlock(&_mutex);
    }
    void Pop(T *out)
    {
        pthread_mutex_lock(&_mutex);
        while (IsEmpty())
        {
            pthread_cond_wait(&_consum_cond, &_mutex);
        }
        *out = _block_queue.front();
        _block_queue.pop();
        pthread_cond_signal(&_produck_cond);
        pthread_mutex_unlock(&_mutex);
    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_produck_cond);
        pthread_cond_destroy(&_consum_cond);
    }

private:
    queue<T> _block_queue;
    int _cap;
    pthread_mutex_t _mutex;
    pthread_cond_t _produck_cond;
    pthread_cond_t _consum_cond;
};
#endif